package com.lst.servlet;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.druid.util.StringUtils;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.dao.OnlineCourseMapper;
import com.lst.entity.request.SportRecordsReqPara;
import com.lst.entity.response.SportRecordsResPara3;
import com.lst.model.OnlineCourse;
import com.lst.model.SportRecords;
import com.lst.model.TrainRecord;
import com.lst.service.SportRecordsService;
import com.lst.utils.DateUtil;
import com.lst.utils.RequestUtils;


/**
 * @ClassName: SportRecordListServlet
 * @Description: 运动记录课程接口
 * 
 */
public class SportRecordListServlet extends BaseServlet {

	/**
	 * @Fields serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	private SportRecordsService sportRecordsService = ctx.getBean(SportRecordsService.class);
	
	 @Autowired
	private OnlineCourseMapper onlineCourseMapper = ctx.getBean(OnlineCourseMapper.class);
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		Date startDate = new Date();
		logger.info("doPost begin: " + startDate);
		SportRecordsResPara3 resPara = new SportRecordsResPara3();

		try {
			SportRecordsReqPara reqPara = getReqPara(request);
			
		if(isCheckField(reqPara,resPara)){
			Integer userid = Integer.valueOf(reqPara.getUserid());
			Integer page = Integer.valueOf(reqPara.getPage());
			Integer pagesize = Integer.valueOf(reqPara.getPagesize());
			
				Map<String, Object> reqMap = new HashMap<String, Object>();		
                reqMap.put("createUser", userid);
				

				 PageBounds pageBounds = new PageBounds(page,pagesize);	
				 List<SportRecords> sportList=sportRecordsService.queryByMap(reqMap,pageBounds);
				 
				 List<TrainRecord> trainRecordList=new ArrayList<TrainRecord>();//训练课程列表

				if (sportList != null && sportList.size() > 0) {
					for (int i = 0; i < sportList.size(); i++) {
						OnlineCourse onlineCourse = onlineCourseMapper.selectByPrimaryKey(sportList.get(i).getCourseId());
						onlineCourse.setUpdatedate(sportList.get(i).getCreateDate());
						String strTime = DateUtil.date2Str(sportList.get(i).getCreateDate2(), "yyyy年MM月");
						if (trainRecordList == null || trainRecordList.size() == 0) {
							TrainRecord trainRecord = new TrainRecord();
							List<OnlineCourse> courseList = new ArrayList<OnlineCourse>();
							courseList.add(onlineCourse);
							trainRecord.setTrainTime(strTime);
							trainRecord.setCourseList(courseList);
							trainRecordList.add(trainRecord);
							
							String strTime2 = DateUtil.date2Str(sportList.get(i).getCreateDate2(), "yyyy-MM");
							Map<String,Object> reqmap2=new HashMap<String,Object>();
							reqmap2.put("createUser",userid);
						    reqmap2.put("monthDate",strTime2);
						    List<SportRecords>  sportRecordsList=sportRecordsService.queryByList(reqmap2);
						    if(sportRecordsList!=null){
						    	trainRecord.setTrainNum(sportRecordsList.size());
						    }
							
						} else {
							int index = 0;
							for (int j = 0; j < trainRecordList.size(); j++) {
								if (trainRecordList.get(j).getTrainTime().equals(strTime)) {
									trainRecordList.get(j).getCourseList().add(onlineCourse);
									index++;
									break;
								}
							}

							if (index == 0) {
								TrainRecord trainRecord = new TrainRecord();
								List<OnlineCourse> courseList = new ArrayList<OnlineCourse>();
								courseList.add(onlineCourse);
								trainRecord.setTrainTime(strTime);
								trainRecord.setCourseList(courseList);
								trainRecordList.add(trainRecord);
								
								String strTime2 = DateUtil.date2Str(sportList.get(i).getCreateDate2(), "yyyy-MM");
								Map<String,Object> reqmap2=new HashMap<String,Object>();
								reqmap2.put("createUser",userid);
							    reqmap2.put("monthDate",strTime2);
							    List<SportRecords>  sportRecordsList=sportRecordsService.queryByList(reqmap2);
							    if(sportRecordsList!=null){
							    	trainRecord.setTrainNum(sportRecordsList.size());
							    }
							}

						}

					}
				}
			
			resPara.setTrainRecordList(trainRecordList);
			
			resPara.setCode(CommCode.M_Y000000);
			resPara.setMessage(CommCode.M_Y000001);
		  }
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);
			logger.error("doPost error: ", e);
		}
		
		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);
			logger.info("SportRecordListServlet jsonResult:" + jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

			logger.info("doPost end run(s): " + DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public SportRecordsReqPara getReqPara(HttpServletRequest request) {

		SportRecordsReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new SportRecordsReqPara());

			reqPara = (SportRecordsReqPara) baseRequest.clone();

			String userid = request.getParameter("userid");
			String page = request.getParameter("page");
			String pagesize = request.getParameter("pagesize");
	
			logger.info("reqPara userid:" + userid);
			logger.info("reqPara page:" + page);
			logger.info("reqPara pagesize:" + pagesize);

	        reqPara.setUserid(userid);
	        reqPara.setPage(page);
	        reqPara.setPagesize(pagesize);

		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		SportRecordsReqPara cdReqPara = (SportRecordsReqPara) reqPara;
		BaseResponse cdResPara = (BaseResponse) resPara;

        if (StringUtils.isEmpty(cdReqPara.getUserid())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage(CommCode.M_P000002);
		}else if (StringUtils.isEmpty(cdReqPara.getPage())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage(CommCode.M_P000009);
		}else if (StringUtils.isEmpty(cdReqPara.getPagesize())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage(CommCode.M_P000010);
		}else {
			flag = true;
		}

		return  flag;
	}

}
